﻿using Abp.Application.Services;
using SportsPlatform.Base;
using SportsPlatform.Dto.SportBusiness.Employee;
using SportsPlatform.Query.SportBusiness.Employee;
using SportsPlatform.WeChat.IWeChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.Consts;
using SportsPlatform.Model.SportBusiness;
using Abp.Domain.Repositories;
using SportsPlatform.Helpers;
using System.Net.Http;
using NPOI.SS.Formula.Functions;
using System.Net;
using Google.Protobuf.WellKnownTypes;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.TenPayV3;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.TenPayV3.Apis;
using Microsoft.AspNetCore.Http;
using System.Collections;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using SportsPlatform.Model.PermissionManagement;
using Senparc.CO2NET.Extensions;
using SportsPlatform.Application.Query.SportBusiness.Employee;

namespace SportsPlatform.WeChat.WeChat
{
    /// <summary>
    /// 移动端登录注册实现
    /// </summary>
    [RemoteService(false)]
    public class LoginService : SportsPlatformAppServiceBase, ILoginService
    {
        private readonly IRepository<Employee, Guid> _employeeRepository;
        private readonly IRepository<Team, Guid> _teamRepository;
        private readonly IRepository<TeamUser, Guid> _teamuserRepository;
        private static TenPayV3Info _tenPayV3Info;
        private readonly BasePayApis _basePayApis;
        private readonly ISenparcWeixinSettingForTenpayV3 _tenpayV3Setting;

        /// <summary>
        /// 获取配置参数
        /// </summary>
        public static TenPayV3Info TenPayV3Info
        {
            get
            {
                if (_tenPayV3Info == null)
                {
                    var key = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);

                    _tenPayV3Info =
                        TenPayV3InfoCollection.Data[key];
                }
                return _tenPayV3Info;
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginService(IRepository<Employee, Guid> employeeRepository, IRepository<Team, Guid> teamRepository,
            IRepository<TeamUser, Guid> teamuserRepository, IHttpContextAccessor context) : base(context)
        {
            _employeeRepository = employeeRepository;
            _teamRepository = teamRepository;
            _teamuserRepository = teamuserRepository;
            _tenpayV3Setting = Senparc.Weixin.Config.SenparcWeixinSetting.TenpayV3Setting;
            _basePayApis = new BasePayApis(_tenpayV3Setting);
        }

        /// <summary>
        /// 移动端用户登录
        /// </summary>
        /// <param name="employeeLoginQuery"></param>
        /// <returns></returns>
        public async Task<ResultDto<EmployeeDto>> EmployeeLogin(EmployeeLoginQuery employeeLoginQuery)
        {
            ResultDto<EmployeeDto> resultDto = new ResultDto<EmployeeDto>();
            try
            {
                #region 获取手机号

                var request_token = $"https://api.weixin.qq.com/cgi-bin/token?appid={TenPayV3Info.AppId}&secret={TenPayV3Info.AppSecret}&grant_type=client_credential";
                var token = "";
                var getres = await request_token.GetAsync();
                JObject obj = (JObject)JsonConvert.DeserializeObject(getres);
                for (int i = 0; i < obj.Count; i++)
                {
                    token = obj["access_token"].ToString();  //这里可以取ja中的值
                    break;
                }

                //获取手机号
                string url = $"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={token}";

                string strContent = "{ \"code\": \"" + employeeLoginQuery.code + "\" }";

                var res = await url.PostAsync(strContent);
                var phone_info = string.Empty;
                for (int i = 0; i < res.Count; i++)
                {
                    phone_info = res["phone_info"].ToJson();  //这里可以取ja中的值
                    break;
                }
                var job = JObject.Parse(phone_info);

                var ph = string.Empty;
                for (int j = 0; j < job.Count; j++)
                {
                    ph = job["phoneNumber"].ToString();  //这里可以取ja中的值
                    break;
                }

                #endregion

                var employeeinfo = await _employeeRepository.FirstOrDefaultAsync(info => info.Phone == ph && info.OpenId == employeeLoginQuery.openId);
                if (employeeinfo != null)
                {

                    var dto = ObjectMapper.Map<EmployeeDto>(employeeinfo);
                    //获取团队集合
                    var teamuserlist = await _teamuserRepository.GetAllListAsync(info => info.EmployeeId == dto.Id);
                    var teams = await _teamRepository.GetAllListAsync();
                    if (teamuserlist != null && teamuserlist.Count() > 0)
                    {
                        List<TeamItem> TeamList = new List<TeamItem>();
                        foreach (var teamuseritem in teamuserlist)
                        {
                            try
                            {
                                TeamItem teamItem = new TeamItem();
                                teamItem.TeamId = teamuseritem.TeamId;
                                teamItem.TeamName = teams.FirstOrDefault(info => info.Id == teamuseritem.TeamId).TeamName;
                                TeamList.Add(teamItem);
                            }
                            catch { }
                        }
                        dto.TeamList = (TeamList != null && TeamList.Count > 0) ? TeamList : null;
                    }
                    if (employeeinfo.OpenId.IsNullAndEmpty())
                    {
                        employeeinfo.OpenId = employeeLoginQuery.openId;
                        employeeinfo.NickName = employeeLoginQuery.nickName;
                        employeeinfo.HeadPortrait = employeeLoginQuery.avatarUrl;
                        employeeinfo.IDNumber = "";
                        employeeinfo.RealName = "";
                        var updateEm = _employeeRepository.Update(employeeinfo);
                        dto.OpenId = updateEm.OpenId;
                        dto.NickName = updateEm.NickName;
                        dto.HeadPortrait = updateEm.HeadPortrait;
                        dto.IsFirst = true;
                    }
                    else
                    {
                        dto.IsFirst = false;
                    }
                    resultDto.Message = "查询成功";
                    resultDto.Data = dto;
                }
                else
                {
                    var em = _employeeRepository.Insert(new Employee
                    {
                        CreateTime = DateTime.Now,
                        HeadPortrait = employeeLoginQuery.avatarUrl,
                        NickName = employeeLoginQuery.nickName,
                        Phone = ph,
                        RegisterTime = DateTime.Now,
                        OpenId = employeeLoginQuery.openId,
                        IDNumber = "",
                        RealName = "",
                        Sex = 1,
                        Sensor = "",
                    });
                    if (em.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Error;
                        resultDto.Message = "注册失败";
                        resultDto.IsSuccess = false;
                        return resultDto;
                    }
                    resultDto.Data = new EmployeeDto
                    {
                        HeadPortrait = em.HeadPortrait,
                        NickName = em.NickName,
                        Phone = em.Phone,
                        OpenId = em.OpenId,
                        Id = em.Id,
                        IDNumber = em.IDNumber,
                        RealName = em.RealName,
                        RegisterTime = em.RegisterTime.ToString("yyyy-MM-dd"),
                        Sensor = em.Sensor,
                        Sex = em.Sex,
                        IsFirst = true
                    };
                    resultDto.Message = "注册成功";

                }
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
                return resultDto;
            }
            resultDto.IsSuccess = true;
            resultDto.Code = HttpResultCode.Success;
            return resultDto;
        }

        /// <summary>
        /// 移动端用户注册
        /// </summary>
        /// <param name="employeeRegisterQuery"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> EmployeeRegister(EmployeeRegisterQuery employeeRegisterQuery)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                //判断手机号是否存在
                if (await _employeeRepository.FirstOrDefaultAsync(info => info.Phone == employeeRegisterQuery.Phone) == null)
                {
                    var employeeinfo = ObjectMapper.Map<Employee>(employeeRegisterQuery);
                    employeeinfo.Create(this._context);
                    employeeinfo.RegisterTime = DateTime.Now;
                    employeeinfo.Sex = CommonHelper.GetSex(employeeRegisterQuery.IDNumber).Equals("男") ? 1 : 0;
                    var employee = await _employeeRepository.InsertAsync(employeeinfo);
                    if (employee == null)
                    {
                        baseResultDto.IsSuccess = true;
                        baseResultDto.Code = HttpResultCode.Success;
                        baseResultDto.Message = "注册成功！";
                    }
                    else
                    {
                        baseResultDto.IsSuccess = false;
                        baseResultDto.Code = HttpResultCode.SqlError;
                        baseResultDto.Message = "注册失败！";
                    }
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "手机号已存在！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 通过openId获取用户信息
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public async Task<ResultDto<EmployeeDto>> GetByOpenId(GetOpenIdQuery query)
        {
            ResultDto<EmployeeDto> resultDto = new ResultDto<EmployeeDto>();
            try
            {
                if (query.OpenId.IsNullOrEmpty())
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "openId不能为空";
                    return resultDto;
                }

                var res = await _employeeRepository.FirstOrDefaultAsync(x => x.OpenId == query.OpenId);

                if (res.IsNullAndEmpty())
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.Message = "未查询到数据";
                    return resultDto;
                }

                resultDto.Code = 200;
                resultDto.Data = new EmployeeDto
                {
                    HeadPortrait = res.HeadPortrait,
                    NickName = res.NickName,
                    Phone = res.Phone,
                    OpenId = res.OpenId,
                    Id = res.Id,
                    IDNumber = res.IDNumber,
                    RealName = res.RealName,
                    RegisterTime = res.RegisterTime.ToString("yyyy-MM-dd"),
                    Sensor = res.Sensor,
                    Sex = res.Sex,
                    IsFirst = false
                };
                resultDto.IsSuccess = true;
                resultDto.Message = "查询成功";

                return resultDto;

            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 验证身份证号
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> CheckIdNumber(Guid employeeId)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var emp = await _employeeRepository.GetAsync(employeeId);
                if (emp.IsNullAndEmpty())
                {
                    result.Code = HttpResultCode.NotData;
                    result.IsSuccess = false;
                    result.Message = "当前用户不存在";
                    return result;
                }
                if (!emp.IDNumber.IsNullAndEmpty())
                {
                    result.Data = true;
                }
                result.Message = "请求成功";
                result.Code = 200;
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }
    }
}
